<template>
	<view class="address-edit-container">
		
		<!-- 表单内容 -->
		<view class="form-container">
			<!-- 选择收货地址按钮 -->
			<view class="select-address-btn" @click="selectAddress">
				<text class="btn-text">选择收货地址</text>
			</view>
			
			<!-- 表单字段 -->
			<view class="form-fields">
				<!-- 收货人 -->
				<view class="form-item">
					<text class="form-label">收货人</text>
					<input 
						class="form-input" 
						placeholder="请输入收货人姓名" 
						v-model="formData.name"
						maxlength="20"
					/>
				</view>
				
				<!-- 手机号码 -->
				<view class="form-item">
					<text class="form-label">手机号码</text>
					<input 
						class="form-input" 
						placeholder="请输入收货人手机号码" 
						v-model="formData.phone"
						type="number"
						maxlength="11"
					/>
				</view>
				
				<!-- 所在区域 -->
				<view class="form-item">
					<text class="form-label">所在区域</text>
					<view class="form-input region-input" @click="selectRegion">
						<text class="region-text" v-if="formData.region">{{ formData.region }}</text>
						<text class="region-placeholder" v-else>请选择所在地区</text>
						<text class="arrow-icon">></text>
					</view>
				</view>
				
				<!-- 详细地址 -->
				<view class="form-item">
					<text class="form-label">详细地址</text>
					<textarea 
						class="form-textarea" 
						placeholder="街道楼牌号等" 
						v-model="formData.address"
						maxlength="100"
					/>
				</view>
				
				<!-- 地址别名 -->
				<view class="form-item">
					<text class="form-label">地址别名</text>
					<input 
						class="form-input" 
						placeholder="请输入地址别名" 
						v-model="formData.alias"
						maxlength="20"
					/>
				</view>
			</view>
			
			<!-- 设为默认地址 -->
			<view class="default-option">
				<view class="checkbox-container" @click="toggleDefault">
					<view class="checkbox" :class="{ checked: formData.isDefault }">
						<text class="check-icon" v-if="formData.isDefault">✓</text>
					</view>
					<text class="checkbox-text">设为默认地址</text>
				</view>
			</view>
		</view>
		
		<!-- 底部保存按钮 -->
		<view class="bottom-bar">
			<view class="save-btn" @click="saveAddress">
				保存
			</view>
		</view>
	</view>
</template>

<script>
	import { addAddress, updateAddress } from '@/api/address.js'
	import { getCurrentMemberId } from '@/utils/userState.js'
	
	export default {
		data() {
			return {
				formData: {
					name: '',
					phone: '',
					region: '',
					address: '',
					alias: '',
					isDefault: false
				},
				isEdit: false,
				editId: null,
				currentMemberId: null // 当前用户的memberId
			}
		},
		onLoad(options) {
			console.log('新增/编辑收货地址页面 onLoad，接收到的参数:', options);
			
			// 获取当前用户的memberId
			this.initMemberId();
			
			// 监听memberId接收事件
			uni.$on('memberIdReceived', (memberId) => {
				this.currentMemberId = memberId;
				console.log('从地址管理页面获取到memberId:', this.currentMemberId);
			});
			
			// 检查是否为编辑模式
			if (options.mode === 'edit' && options.addressData) {
				this.isEdit = true;
				try {
					// 解析传递过来的地址数据
					const addressData = JSON.parse(decodeURIComponent(options.addressData));
					console.log('编辑模式，接收到的地址数据:', addressData);
					
					this.editId = addressData.id;
					
					// 将地址数据转换为表单数据格式
					this.formData = {
						name: addressData.receiverName || '',
						phone: addressData.receiverPhone || '',
						region: `${addressData.province || ''},${addressData.city || ''},${addressData.district || ''}`,
						address: addressData.detailAddress || '',
						alias: addressData.addressAlias || '',
						isDefault: addressData.isDefault === 1
					};
					
					console.log('转换后的表单数据:', this.formData);
					console.log('formData.name:', this.formData.name);
					console.log('formData.phone:', this.formData.phone);
					console.log('formData.region:', this.formData.region);
					console.log('formData.address:', this.formData.address);
					console.log('formData.alias:', this.formData.alias);
					console.log('formData.isDefault:', this.formData.isDefault);
					
					// 强制更新视图
					this.$forceUpdate();
				} catch (error) {
					console.error('解析地址数据失败:', error);
					uni.showToast({
						title: '数据解析失败',
						icon: 'none'
					});
				}
			}
		},
		onUnload() {
			// 清理数据
			this.formData = {
				name: '',
				phone: '',
				region: '',
				address: '',
				alias: '',
				isDefault: false
			};
			
			// 移除事件监听
			uni.$off('memberIdReceived');
		},
		methods: {
			// 初始化当前用户的memberId
			async initMemberId() {
				try {
					// 使用用户状态管理工具获取memberId
					const memberId = getCurrentMemberId();
					if (memberId) {
						this.currentMemberId = memberId;
						console.log('从用户状态管理获取到memberId:', this.currentMemberId);
						return;
					}
					
					// 如果还没有memberId，尝试从地址列表获取
					uni.$emit('requestMemberId');
					
					// 等待一段时间让其他页面响应
					await new Promise(resolve => setTimeout(resolve, 100));
					
					// 如果都没有，使用默认值（临时方案）
					if (!this.currentMemberId) {
						this.currentMemberId = 1535;
						console.log('使用默认memberId:', this.currentMemberId);
					}
				} catch (error) {
					console.error('获取memberId失败:', error);
					// 使用默认值
					this.currentMemberId = 1535;
					console.log('使用默认memberId:', this.currentMemberId);
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 选择收货地址（地图选择）
			selectAddress() {
				uni.showToast({
					title: '地图选择功能开发中',
					icon: 'none'
				});
			},
			
			// 选择所在区域
			selectRegion() {
				uni.showActionSheet({
					itemList: ['广东省,汕头市,潮阳区,和平镇', '广东省,深圳市,南山区,科技园', '北京市,朝阳区,三里屯', '上海市,浦东新区,陆家嘴'],
					success: (res) => {
						const regions = ['广东省,汕头市,潮阳区,和平镇', '广东省,深圳市,南山区,科技园', '北京市,朝阳区,三里屯', '上海市,浦东新区,陆家嘴'];
						this.formData.region = regions[res.tapIndex];
					}
				});
			},
			
			// 切换默认地址
			toggleDefault() {
				this.formData.isDefault = !this.formData.isDefault;
				
				// 如果设置为默认地址，显示提示信息
				if (this.formData.isDefault) {
					uni.showToast({
						title: '将设为默认地址',
						icon: 'none',
						duration: 1500
					});
				}
			},
			

			

			
			// 保存地址
			async saveAddress() {
				// 验证memberId
				if (!this.currentMemberId) {
					uni.showToast({
						title: '用户未登录，请先登录',
						icon: 'none'
					});
					return;
				}
				
				console.log('保存地址，当前memberId:', this.currentMemberId);
				
				// 表单验证
				if (!this.formData.name.trim()) {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.phone.trim()) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					});
					return;
				}
				
				// 验证手机号码格式
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!phoneRegex.test(this.formData.phone.trim())) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.region) {
					uni.showToast({
						title: '请选择所在区域',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.address.trim()) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					});
					return;
				}
				
				// 显示加载提示
				uni.showLoading({
					title: '保存中...'
				});
				
				try {
					// 解析区域信息
					const regionParts = this.formData.region.split(',');
					const province = regionParts[0] || '';
					const city = regionParts[1] || '';
					const district = regionParts[2] || '';
					
					console.log('解析的区域信息:', { province, city, district });
					console.log('当前表单数据:', this.formData);
					
					// 构建地址数据
					const addressData = {
						receiverName: this.formData.name,
						receiverPhone: this.formData.phone,
						province: province,
						city: city,
						district: district,
						detailAddress: this.formData.address,
						addressAlias: this.formData.alias,
						isDefault: this.formData.isDefault ? 1 : 0,
						memberId: this.currentMemberId // 使用动态获取的memberId
					};
					
					console.log('构建的地址数据:', addressData);
					
					let response;
					
					if (this.isEdit) {
						// 编辑模式：更新地址
						addressData.id = this.editId;
						console.log('编辑模式，更新地址数据:', addressData);
						console.log('调用 updateAddress API...');
						response = await updateAddress(addressData);
						console.log('updateAddress API 响应:', response);
					} else {
						// 新增模式：添加地址
						console.log('新增模式，添加地址数据:', addressData);
						console.log('调用 addAddress API...');
						response = await addAddress(addressData);
						console.log('addAddress API 响应:', response);
					}
					
					// 先隐藏加载提示
					uni.hideLoading();
					
					if (response && response.code === 200) {
						// 保存成功
						const successMessage = this.isEdit ? '修改成功' : '添加成功';
						
						if (this.formData.isDefault) {
							uni.showToast({
								title: successMessage + '，已设为默认地址',
								icon: 'success',
								duration: 2000
							});
						} else {
							uni.showToast({
								title: successMessage,
								icon: 'success'
							});
						}
						
						// 通知地址管理页面刷新数据
						uni.$emit('refreshAddressList');
						
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						// 保存失败
						uni.showToast({
							title: response?.msg || '保存失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('保存地址失败:', error);
					// 确保在错误情况下也隐藏加载提示
					uni.hideLoading();
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style scoped>
	.address-edit-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}
	
	/* 表单容器 */
	.form-container {
		background-color: #fff;
		margin: 20rpx;
		border-radius: 12rpx;
		padding: 30rpx;
	}
	
	/* 选择收货地址按钮 */
	.select-address-btn {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #ff4444;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
		background-color: #fff;
	}
	
	.btn-text {
		font-size: 28rpx;
		color: #ff4444;
	}
	
	/* 表单字段 */
	.form-fields {
		display: flex;
		flex-direction: column;
		gap: 0;
	}
	
	.form-item {
		display: flex;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.form-item:last-child {
		border-bottom: none;
	}
	
	.form-label {
		width: 160rpx;
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}
	
	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		background-color: transparent;
		border: none;
		outline: none;
	}
	
	.form-textarea {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		background-color: transparent;
		min-height: 80rpx;
		line-height: 1.4;
		border: none;
		outline: none;
		resize: none;
	}
	
	/* 区域选择 */
	.region-input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		cursor: pointer;
	}
	
	.region-text {
		font-size: 28rpx;
		color: #333;
	}
	
	.region-placeholder {
		font-size: 28rpx;
		color: #999;
	}
	
	.arrow-icon {
		font-size: 24rpx;
		color: #ccc;
	}
	
	/* 默认地址选项 */
	.default-option {
		margin-top: 30rpx;
		padding-top: 30rpx;
		border-top: 1rpx solid #f0f0f0;
	}
	
	.checkbox-container {
		display: flex;
		align-items: center;
		cursor: pointer;
	}
	
	.checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #ddd;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		background-color: #fff;
		transition: all 0.3s ease;
	}
	
	.checkbox.checked {
		background-color: #ff4444;
		border-color: #ff4444;
	}
	
	.check-icon {
		font-size: 20rpx;
		color: #fff;
		font-weight: bold;
	}
	
	.checkbox-text {
		font-size: 28rpx;
		color: #333;
	}
	
	/* 底部保存按钮 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
	}
	
	.save-btn {
		width: 100%;
		height: 80rpx;
		background-color: #ff4444;
		color: #fff;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: bold;
	}
</style> 